package org.xx.armory.commons;

/**
 * 实现具有生命周期的对象的基本功能。
 */
public abstract class AbstractLifeCycle
        implements LifeCycle {
    private boolean active;
    private long initializedTime;

    /**
     * 构造AbstractLifeCycle对象的实例。
     */
    protected AbstractLifeCycle() {
        this.active = false;
        this.initializedTime = 0L;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize()
            throws Exception {
        assertNotInitialized();
        this.active = true;

        this.initializedTime = System.currentTimeMillis();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void dispose()
            throws Exception {
        assertInitialized();
        this.active = false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean isActive() {
        return active;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final long getSurvivalTime() {
        if (this.active) {
            return (System.currentTimeMillis() - this.initializedTime) / 1000;
        } else {
            return 0L;
        }
    }

    /**
     * 检测当前对象是否已初始化。
     *
     * @throws IllegalStateException
     *         如果当前对象尚未初始化。
     */
    protected final void assertInitialized() {
        if (!this.active) {
            throw new IllegalStateException("object is not initialized");
        }
    }

    /**
     * 检测当前对象是否尚未初始化。
     *
     * @throws IllegalStateException
     *         如果当前对象已初始化。
     */
    protected final void assertNotInitialized() {
        if (this.active) {
            throw new IllegalStateException("object already initialized");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void close()
            throws Exception {
        dispose();
    }
}
